import common from './common.js'
import login from './login.js'
const app = getApp()

var outTime = 1000, //请求超过此时间就显示loading
	timer = null;

class request {
	
	static async go(callback,url,data,method="GET",contentType="application/x-www-form-urlencoded",mod=0){
		await login.checkLogin() 
		if(app.globalData.userInfo){
			data.token = app.globalData.userInfo.token
		}
		if(mod == 1){
			url = url + "?token=" + app.globalData.userInfo.token
		}
		clearTimeout(timer)
		showLoading(url)
		uni.request({
			url:app.globalData.baseUrl + url,
			data,
			method,
			header:{
				"Content-Type":contentType
			},
			success(e){
				clearTimeout(timer)
				uni.hideLoading()
				if(e.data.code == 200){
					callback(e.data)
				}else{
					handleCode(e.data)
				}
			},
			fail(err) {
				clearTimeout(timer)
				uni.hideLoading()
				uni.showToast({
					title:"请求失败",
					icon:'none'
				})
			}
		})
	}
}

//展示loading
function showLoading(url){
	let title = ""
	switch(url){
		case '/Login/xcxlogin':
		case '/Login/xcxplogin':
		case '/qywechat/login':
		case '/qywechat/mlogin':
			title = '登录中'
			uni.showLoading({
				title,
				mask:true
			})
		break;
		case '/Jwteachertask/add': // 布置作业等提交功能显示loading防止误触、重复点击
		case '/tongzhi/xttz_add':
		case '/Jwteachertask/taskhandle':
			title = '提交中'
			uni.showLoading({
				title,
				mask:true
			})
		break;
		default:
			title = '加载中'
			timer = setTimeout(()=>{
				uni.showLoading({
					title,
					mask:true
				})
			},outTime)
		break;
	}
}

// 处理code
function handleCode(data){
	let code = data.code
	let message = data.message
	switch(code){
		case 300:
		case "300":
			uni.showToast({
				icon:"none",
				title:"登录失效",
				duration:800
			})
			setTimeout(()=>{
				common.go('/pages/index/login')
			},800)
		break;
		case 103: // 企业微信登录->没有绑定手机号，请先绑定手机号->进入手机登录页
		case "103":
			app.globalData.open_userid = data.data.open_userid // 保存open_userid
			uni.showToast({
				icon:"none",
				title:message,
				duration:800
			})
			setTimeout(()=>{
				common.go('/pages/pack/login/login-phone')
			},800)
		break;
		default:
			uni.showToast({
				icon:"none",
				title:message,
				duration:800
			})
		break;
	}
}

export default request